import { BASE_URL } from "@/utils/constants.js";
  
// const BASE_URL = 'https://riddle.miyucaicai.cn/v1/';

// Define the maximum number of retries to prevent infinite loops
const MAX_RETRY_COUNT = 1;

// Utility function to make an HTTP request with a login token and retry mechanism
export const request =(config={})=>{	
	let {
		url,
		data={},
		method="GET", //默认GET
		header={},
		retryCount = 0
	} = config 
	return new Promise((resolve, reject) => {
		let fullUrl = BASE_URL + url
		const token = uni.getStorageSync('token'); // Get the token from storage
		uni.request({
			url: fullUrl,
			data: data,
			method: method || 'GET',
			header: {
				'token': `${token}`, // Attach the token
				'platform':process.env.UNI_PLATFORM 
			},
			success: async (response) => {
				if (response.statusCode === 200) {
					resolve(response.data);
				} else if (response.statusCode === 401 && retryCount < MAX_RETRY_COUNT) {
					// Token is expired or not logged in and retry count is less than the max limit
					console.log('Token expired or not logged in, attempting to re-login...');
					try {
						await reLogin(); // Call login function
						const retryResponse = await request({url, data, method, retryCount:retryCount+1}); 
						resolve(retryResponse);
					} catch (loginError) {
						reject('Re-login failed');
					}
				} else {
					// Either the token is invalid and we have reached the max retry limit, or another error occurred
					reject(response.data);
				}
			},
			fail: (error) => {
				reject(error);
			}
		});
	});
};

// Function to handle re-login (e.g., using uni.login API for WeChat Mini Program)
export const reLogin = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: (loginRes) => {
				if (loginRes.code) {
					// Send loginRes.code to the server to get a new token
					uni.request({
						url: BASE_URL+'/v1/wx/getSession?desc=law&code='+loginRes.code, // 需要 desc配对小程序appId
						method: 'GET',
						success: (res) => {
							if (res.data && res.data.data) {
								// Save the new token
								uni.setStorageSync('token', res.data.data.authKey);
								uni.setStorageSync('myid', res.data.data.userId);
								uni.setStorageSync('userInfo', res.data.data);
								resolve();
							} else {
								reject('Login failed');
							}
						},
						fail: (err) => {
							reject(err);
						}
					});
				} else {
					reject('uni.login failed to get the code');
				}
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};